// pages/cart/cart.js
import {
  getSetting,
  chooseAddress,
  openSetting,showModal,showToast
} from '../../utils/asyncWx.js'
import regeneratorRuntime from '../../lib/runtime/runtime'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allchecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  //监听页面显示
  onShow: function () {
    //从缓存中取出收货地址
    const address = wx.getStorageSync('address')
    //从缓存中取出购物车商品信息
    const cart = wx.getStorageSync('cart') || []
    this.setData({
      address
    })
    //调用方法
    this.setCart(cart)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  //----------监听点击事件----------
  async getAddress() {

    //----------旧代码----------
    // //1.获取权限状态
    // wx.getSetting({
    //   complete: (res) => {
    //     const scopeAddress = res.authSetting["scope.address"]
    //     if (scopeAddress === true || scopeAddress === undefined) {
    //       //2.获取用户地址
    //       wx.chooseAddress({
    //         complete: (res1) => {
    //           console.log(res1)
    //         },
    //       })
    //     } else {
    //       //2. 诱导用户授权
    //       wx.openSetting({
    //         complete: (res2) => {
    //           console.log(res2)
    //           //2.获取用户地址
    //           wx.chooseAddress({
    //             complete: (res3) => {
    //               console.log(res3)
    //             },
    //           })
    //         },
    //       })
    //     }
    //   },
    // })

    try {
      //----------新代码----------

      //1. 获取权限状态
      const res1 = await getSetting()
      const scopeAddress = res1.authSetting["scope.address"]

      //2.判断权限状态
      if (scopeAddress === false) {

        //3.先诱导用户打开授权
        await openSetting()
      }

      //3.调用获取收货地址API
      const address = await chooseAddress()
      address.all=address.provinceName+address.cityName+address.countyName+address.detailInfo
      //4.将收货地址加入缓存中
      wx.setStorageSync('address', address)
    } catch (error) {
      console.log(error)
    }
  },

  //监听购物车列表复选框点击
  checkboxChange(e) {
    //获取商品对象
    const goods_id = e.currentTarget.dataset.id
    //获取购物车数组
    let {
      cart
    } = this.data
    //商品选中状态取反
    let index = cart.findIndex(v => v.goods_id === goods_id)
    cart[index].checked = !cart[index].checked

    //调用方法
    this.setCart(cart)

  },

  //监听全选复选框点击
  allcheckboxChange() {
    //获取购物车数组和全选属性
    let {
      cart,
      allchecked
    } = this.data
    //全选反选
    allchecked = !allchecked
    cart.forEach(v => v.checked = allchecked)
    //调用方法
    this.setCart(cart)
  },

  //监听数量点击事件
  async handleCounter(e){
    const goods_id=e.currentTarget.dataset.id
    const operation=e.currentTarget.dataset.operation
    const {cart}=this.data
    let index=cart.findIndex(v=>v.goods_id===goods_id)
    //判断是否删除
    if(cart[index].num===1&operation===-1){
      //弹窗提示
      const res=await showModal({content:"是否删除该物品?"})
      if (res.confirm) {
        cart.splice(index,1)
        this.setCart(cart)
      }
    }else{
      cart[index].num+=operation
      //调用方法
      this.setCart(cart)
    }
  },
  //监听点击结算
  async handlePay(){
    const {totalNum,address}=this.data;
    //判断有无收货地址
    if(!address.userName){
      await showToast({title:"您还没有选择收获地址"})
      return
    }
    //判断购物车中是否有商品
    if(totalNum===0){
      await showToast({title:"您还没有选择商品"})
      return
    }

    wx.navigateTo({
      url: '/pages/pay/pay',
    })
  },

  //重新计算购物车数据，全选，总价格，总数量
  setCart(cart) {

    //重新计算全选 总价格和总数量
    //计算全选
    // const allchecked=cart.length?cart.every(v=>v.checked):false
    let allchecked = true
    //计算商品价格和数量
    let totalPrice = 0;
    let totalNum = 0
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.goods_price * v.num
        totalNum += v.num
      } else {
        allchecked = false
      }
    })
    //判断数组是否为空
    allchecked = cart.length ? allchecked : false
    //把购物车数组再次填充回data和缓存中
    this.setData({
      cart,
      totalPrice,
      totalNum,
      allchecked
    })
    wx.setStorageSync('cart', cart)
  }

})